package com.itheima.travel.service.impl;

import com.itheima.travel.mapper.UserMapper;
import com.itheima.travel.pojo.User;
import com.itheima.travel.pojo.UserExample;
import com.itheima.travel.req.UserVo;
import com.itheima.travel.service.UserService;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.MD5Coder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HttpSession session;

    @Override
    public boolean registerUser(UserVo userVo) {

        //属性拷贝：将userVo属性的值拷贝到user中。
        User user = new User();
        BeanConv.toBean(userVo,user);

        //用户密码md5加密
        user.setPassword(MD5Coder.md5Encode(user.getPassword()));
        //1.将数据插入到数据库
        int num = userMapper.insert(user);
        //2.将用户数据存放到session
        if (num==1){
            session.setAttribute(session.getId(),userVo);
        }

        return num==1;
    }


    @Override
    public UserVo loginUser(String username, String password) {

        UserVo userVo = new UserVo();
        //密码加密去数据查询
        password = MD5Coder.md5Encode(password);
        //1.判断数据库
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username)
                .andPasswordEqualTo(password);
        List<User> users = userMapper.selectByExample(userExample);
        //2.如果存在，用户信息存档到session
        if(users.size()==1){
            BeanConv.toBean(users.get(0),userVo);
            session.setAttribute(session.getId(),userVo);
        }
        return userVo;
    }


    @Override
    public boolean logoutUser() {

        //清空session即可
        session.invalidate();

        return true;
    }

    @Override
    public boolean isLogin() {

        //判断session中是否有用户信息
        Object obj = session.getAttribute(session.getId());
        return obj!=null;
    }


    @Override
    public UserVo getCurrentUser() {
        //从session中获取
        return (UserVo) session.getAttribute(session.getId());
    }
}
